package com.zaoshui.hudada.controller;

import com.zaoshui.hudada.common.BaseResponse;
import com.zaoshui.hudada.common.ErrorCode;
import com.zaoshui.hudada.common.ResultUtils;
import com.zaoshui.hudada.exception.BusinessException;
import com.zaoshui.hudada.exception.ThrowUtils;
import com.zaoshui.hudada.mapper.StatisticsMapper;
import com.zaoshui.hudada.model.dto.statistics.AppAnswerStatisticsDTO;
import com.zaoshui.hudada.model.dto.statistics.HotAppStaticsDTO;
import com.zaoshui.hudada.model.entity.App;
import com.zaoshui.hudada.model.entity.User;
import com.zaoshui.hudada.model.enums.UserRoleEnum;
import com.zaoshui.hudada.service.AppService;
import com.zaoshui.hudada.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/statistics")
public class StatisticsController {

    @Resource
    private StatisticsMapper statisticsMapper;

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    @GetMapping("/hotApp")
    public BaseResponse<List<HotAppStaticsDTO>> getHotAppStatistics() {
        return ResultUtils.success(statisticsMapper.getHotAppStatics());
    }

    @GetMapping("/appAnswer")
    public BaseResponse<List<AppAnswerStatisticsDTO>> getAppAnswerStatistics(Long appId, HttpServletRequest httpServletRequest) {
        //校验传过来的参数
        ThrowUtils.throwIf(appId == null || appId < 0, ErrorCode.PARAMS_ERROR);

        //获取登录用户
        User loginUser = userService.getLoginUser(httpServletRequest);
        //根据appId 查询出用户信息
        App app = appService.getById(appId);
        User appUser = userService.getById(app.getUserId());
        //判断身份
        if (!loginUser.equals(appUser) && !loginUser.getUserRole().equals(UserRoleEnum.ADMIN.getValue())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        return ResultUtils.success(statisticsMapper.getAppAnswerStatistics(appId));
    }

}
